import axios from 'axios'
import { Message } from 'element-ui'
import store from '../../store/store';
// 创建axios实例
const service = axios.create({
  baseURL: "http://127.0.0.1:5000/", // api的base_url
  timeout: 5000 // 请求超时时间
})

// request拦截器
service.interceptors.request.use(config => {
  if(store.getToken){
    config.headers['token'] = store.getToken;
  }else{
    if(localStorage.getItem("token")){
      config.headers['token'] = localStorage.getItem("token");
    }
  }
  if(store.getClient){
    config.headers['client'] = store.getClient;
  }else{
    if(localStorage.getItem("client")){
      config.headers['client'] =localStorage.getItem("client");
    }
  }
  return config
}, error => {
  // Do something with request error
  console.log(error) // for debug
  Promise.reject(error)
})

// respone拦截器
service.interceptors.response.use(
  response => {
    console.log(response)
    let data=response
    if(data.status===401){
      this.$message.error('登录超时');
      this.go("/login")
      localStorage.clear();
      store.setLoginOut
      this.goLogin=true;
      location.reload()
      return Promise.reject('error')
    }
    if(data.status===402){
      this.$message.error('编辑保存失败，请核实数据后重试');
    }
    if(data.status===403){
      this.$message.error('您无权限进行该操作');
    }
    if(data.status===405){
      this.$message.error('创建失败，请核实数据后重试');
    }
    if(data.status===406){
      this.$message.error('后台操作异常,删除失败');
    }
    if(data.status===500){
      this.$message.error('后台操作异常,请稍后再试');
    }
    if(data.status===501){
      this.$message.error('用户过期，请重新登录');
      this.go("/login")
      localStorage.clear();
      store.setLoginOut
      this.goLogin=true;
      location.reload()
      return Promise.reject('error')
    }else {
      return response.data
    }
  },
  error => {
    console.log('err' + error)// for debug
    Message({
      message: error.message,
      type: 'error',
      duration: 5 * 1000
    })
    return Promise.reject(error)
  }
)

export default service
